const { src,dest,parallel,series,watch } = require('gulp')
// cnpm install gulp-sass node-sass --dev
// cnpm install --save-dev gulp-babel babel-core babel-preset-env
const sass = require('gulp-sass')(require('sass'));
const useref = require('gulp-useref')
const uglify = require('gulp-uglify')
const gulpIf = require('gulp-if')
const cleanCss = require('gulp-clean-css')
const htmlmin = require('gulp-htmlmin')
const loadPlugins = require('gulp-load-plugins')

const browerSync = require('browser-sync')
// const { watch } = require('browser-sync')
const del = require('del')

const bs = browerSync.create()
const plugins = loadPlugins()       
//loadPulgins和gulp-sass一起使用会找不到gulp-sass  
//gulp-sass版本为5及以上不再支持gulp-load-plugins



const clear = ()=> {
    return del(['dist','temp'])
}
const data = {
  menus: [
    {
      name: 'Home',
      icon: 'aperture',
      link: 'index.html'
    },
    {
      name: 'Features',
      link: 'features.html'
    },
    {
      name: 'About',
      link: 'about.html'
    },
    {
      name: 'Contact',
      link: '#',
      children: [
        {
          name: 'Twitter',
          link: 'https://twitter.com/w_zce'
        },
        {
          name: 'About',
          link: 'https://weibo.com/zceme'
        },
        {
          name: 'divider'
        },
        {
          name: 'About',
          link: 'https://github.com/zce'
        }
      ]
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}
const style = ()=> {
    return src('src/assets/styles/*.scss',{ base: 'src' })
    .pipe(sass())
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}
const script = ()=> {
    return src('src/assets/scripts/*.js',{ base: 'src' })
    .pipe(plugins.babel(
        { "presets": ["@babel/preset-env"] }
    ))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const page = () =>{
    return src('src/**/*.html',{ base: 'src' })
    .pipe(plugins.swig({ data, defaults: { cache: false } }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// image font extra 这三个任务我们只需要在build打包上线时才需要做 ，
// 所以不需要单独放在temp文件夹上，放在temp文件夹上的任务是哪些会被useref影响到的（合并 压缩）
const image = ()=> {
    return src('src/assets/images/**',{ base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
const font = ()=> {
    return src('src/assets/fonts/**',{ base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = ()=> {
    return src('public/**',{ base: 'public' })
    .pipe(dest('dist'))
}


const serve = ()=>{
    // 监听文件，发生修改触发 bs.init 中的files，实现修改源代码页面同步
    watch('src/assets/styles/*.scss',style)
    watch('src/assets/script/*.js',script)
    watch('src/*.html',page)
    // watch('src/assets/images/**',image)
    // watch('src/assets/fonts/**',font)
    // watch('public/**',extra)
    watch([
        'src/assets/images/**',
        'src/assets/fonts/**',
        'public/**',
    ],bs.reload)
    bs.init({
        notify: false,          // 不显示在浏览器中的任何通知。
        port: 8080,             // 端口号
        // open: false,         // 服务开启后是否自动打开页面
        // files: 'src/**',       // 监听dist文件夹下所有文件修改，页面自动更新
        // 使用内置的静态服务器创建基本的HTML / JS / CSS的网站
        server: {
            baseDir: ['temp','src','public'],    
            routes: {
                '/node_modules':'node_modules'
            }
        }
    })
}

// 合并&&压缩
const merge = ()=>{
    // gulp-useref
    // 对html页面中同一个构建注释中的的js，css引用进行资源合并,合并成一个js和css文件，但
    // 它只是做文件的合并并不能压缩
    // 使用gulp-useref前dist文件夹中html文件里的构建注释内的资源引用
    //      <!-- build:js assets/scripts/vendor.js -->
    //          <script src="/node_modules/jquery/dist/jquery.js"></script>
    //          <script src="/node_modules/popper.js/dist/umd/popper.js"></script>
    //          <script src="/node_modules/bootstrap/dist/js/bootstrap.js"></script>
    //      <!-- endbuild -->
    //      <!-- build:js assets/scripts/main.js -->
    //          <script src="assets/scripts/main.js"></script>
    //      <!-- endbuild -->

    // 使用后  合并为一个资源文件  删除构建注释
    //    <script src="assets/scripts/vendor.js"></script>
    //    <script src="assets/scripts/main.js"></script>

    return src('temp/*.html',{ base:'temp' })
        .pipe(useref({ searchPath: ['temp', '.'] }))
        // gulp-htmlmin gulp-uglify gulp-clean-css
        // gulp-if
        // 压缩 js html css
        .pipe(gulpIf(/\.js$/,uglify()))
        .pipe(gulpIf(/\.css$/,cleanCss()))
        .pipe(gulpIf(/\.html$/,htmlmin({ 
            collapseWhitespace: true,    //折叠html空白格
            minifyCSS: true,
            minifyJS: true
        })))
        .pipe(dest('dist'))
}


// const compile = parallel(style, script, page, image, font)
const compile = parallel(style, script, page)

// 上线前的任务
const build = series(
    clear,
    parallel(
        // 处理html js css 并行任务compile和文件合并压缩的merge具有依赖关系，
        // 故这两个任务使用串行任务series来组合，先处理html js css 再做合并压缩
        series(compile,merge),  
        image, 
        font, 
        extra
    )
) 
const develop = series(compile,serve)
module.exports = {
    clear,
    // compile,
    build,
    develop,
    // merge
}